package com.emm.yixun.customer.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jws.WebService;

import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.UserTask;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.history.ProcessInstanceHistoryLog;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.basic.service.CustomerService;
import com.emm.yixun.basic.service.DataPermissionService;
import com.emm.yixun.basic.service.DictionaryService;
import com.emm.yixun.basic.service.FamilyMemberService;
import com.emm.yixun.basic.service.NoticeService;
import com.emm.yixun.basic.service.PayDepositService;
import com.emm.yixun.basic.service.ProjectRoomService;
import com.emm.yixun.basic.service.ProjectService;
import com.emm.yixun.basic.service.ProjectSettingService;
import com.emm.yixun.basic.service.UserService;
import com.emm.yixun.common.app.base.CommonResDTO;
import com.emm.yixun.common.constant.SysConstants;
import com.emm.yixun.common.enums.ResultEnum;
import com.emm.yixun.common.exception.ResponseCode;
import com.emm.yixun.common.exception.XFUNExceptionCode;
import com.emm.yixun.common.model.Customer;
import com.emm.yixun.common.model.Dictionary;
import com.emm.yixun.common.model.PayDeposit;
import com.emm.yixun.common.model.Project;
import com.emm.yixun.common.model.ProjectRoom;
import com.emm.yixun.common.model.ProjectSetting;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.BusinessAbnormaDto;
import com.emm.yixun.common.model.dto.CustomerDto;
import com.emm.yixun.common.model.dto.DictionaryDto;
import com.emm.yixun.common.model.dto.FamilyMemberDto;
import com.emm.yixun.common.model.dto.NoticeDto;
import com.emm.yixun.common.model.dto.PayDepositDto;
import com.emm.yixun.common.model.dto.ProjectSettingDto;
import com.emm.yixun.common.model.enums.AuditStatusEnum;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.model.enums.IsPaydepositEnum;
import com.emm.yixun.common.model.enums.MemberTypeEnum;
import com.emm.yixun.common.model.enums.RoomStatusEnum;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.page.PageUtil;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.BeanUtil;
import com.emm.yixun.common.utils.MsgUtil;
import com.emm.yixun.customer.service.PayDepositServiceFacade;
import com.emm.yixun.customer.service.impl.app.ActivitiProcessServiceImpl;

@Service("payDepositServiceFacade")
@WebService(name = "com.emm.yixun.customer.service.PayDepositServiceFacade")
public class PayDepositServiceFacadeImpl implements PayDepositServiceFacade {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private PayDepositService service;
	@Autowired
	private ProjectRoomService projectRoomService;
	@Autowired
	private FamilyMemberService familyMemberService;
	@Autowired
	private CustomerService customerService;
	@Autowired
	private UserService userService;
	@Autowired
	private DictionaryService dictionaryService;
	@Autowired
	private NoticeService noticeService;
	@Autowired
	private ProjectService projectService;
	@Autowired
	private ProjectSettingService projectSettingService;
	@Autowired
	private RepositoryService repositoryService;
	@Autowired
	private HistoryService historyService;
	@Autowired
	private DataPermissionService dataPermissionService;
	@Autowired
	private ActivitiProcessServiceImpl activitiProcessService;

	@Autowired
	private PayDepositTransactionalService payDepositTransactionalService;

	@Override
	public Response<PayDepositDto> save(PayDepositDto dto) {
		Response<PayDepositDto> response = new Response<PayDepositDto>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("保存"));
				return response;
			}
			com.emm.yixun.common.model.ProjectRoom projectRoom = projectRoomService.selectById(dto.getRoomId());
			if (null != projectRoom) {
				dto.setAccessCode(projectRoom.getProjectCode());
				dto.setProjectId(projectRoom.getProjectId());

			}
			PayDepositDto mDto = service.create(dto);
			if (null == mDto) {
				response.fail("80000", "保存数据错误");
				return response;
			}
			response.success(mDto);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Integer> updateByPrimaryKey(PayDepositDto dto, Boolean selective) {
		Response<Integer> response = new Response<Integer>();
		try {
			if (null == selective || null == dto || null == dto.getId()) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("更新"));
				return response;
			}

			if (selective) {
				int count = service.update(dto);
				if (count > 0) {
					response.success(Integer.valueOf(count));
				} else {
					response.fail("90001", "更新数据失败");
				}
			} else {
				response.fail("90000", "暂未实现,修改参数selective=true即可");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("更新数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Integer> deleteByPrimaryKey(Long id) {
		Response<Integer> response = new Response<Integer>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("删除"));
				return response;
			}
			PayDepositDto mDto = new PayDepositDto();
			mDto.setId(id);
			int count = service.destroy(mDto);
			if (count > 0) {
				response.success(Integer.valueOf(count));
			} else {
				response.fail("90001", "删除数据失败");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("删除数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<PayDeposit> findById(Long id) {
		Response<PayDeposit> response = new Response<PayDeposit>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			PayDeposit entity = service.selectById(id);
			if (null == entity) {
				response.fail("90001", "主键查询数据失败");
			} else {
				response.success(entity);
				;
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public ResponseList<PayDeposit> findByDto(PayDepositDto dto) {
		ResponseList<PayDeposit> response = new ResponseList<PayDeposit>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<PayDeposit> list = service.selectListByDto(dto);
			if (null == list) {
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public ResponseList<PayDeposit> findByDtoJ(PayDepositDto dto) {
		ResponseList<PayDeposit> response = new ResponseList<PayDeposit>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<PayDeposit> list = service.selectListByDtoJ(dto);
			if (null == list) {
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Page<PayDeposit> findPageByDto(PayDepositDto dto, Integer begin, Integer row) {
		Page<PayDeposit> response = new Page<PayDeposit>();
		try {
			if (null == dto || null == begin || null == row) {
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			Page<PayDeposit> page = service.getPageModel(dto, begin, row);
			if (null == page.getRows()) {
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			response = page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}", e);
		}
		return response;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.emm.yixun.customer.service.PayDepositServiceFacade#getPayDepositList(com.emm.yixun.common.app.
	 * GetPayDepositListReqDto)
	 */
	@Override
	public Response<Page<PayDepositDto>> getPayDepositList(PayDepositDto reqDto, Integer pageSize, Integer pageNumber) {
		Response<Page<PayDepositDto>> resDto = new Response<Page<PayDepositDto>>();
		try {
			// 1.获取客户认筹列表
			// 数据权限
			if (SysConstants.openDataPermission) {
				String dataPermission = dataPermissionService.dataPermissionCondition(reqDto.getPermissionUserId(),
						reqDto.getResourcesCode(), reqDto.getPrefix(), reqDto.getColumnName());
				String[] dataPermissionArr = dataPermission.split(":");
				if ("00".equals(dataPermissionArr[0])) {
					resDto.setResultMessage(XFUNExceptionCode.USER_PRODUCTNOEXIST.getDesin());
					resDto.setSuccess(false);
					return resDto;
				}
				reqDto.setDataPermission(dataPermissionArr[1]);
			}

			Page<PayDepositDto> payDepositPage = service.getPayDepositDtoList(reqDto,
					PageUtil.begin(pageNumber, pageSize), pageSize);
			payDepositPage.setPageSize(pageSize);
			resDto.setSuccess(true);
			resDto.setEntity(payDepositPage);
			return resDto;
		} catch (Exception e) {
			logger.error("查询分页数据错误：{}", e);
			resDto.setSuccess(false);
			return resDto;
		}
	}

	@Override
	public Response<Boolean> changeService(String params, User user) throws Exception {
		Response<Boolean> response = new Response<Boolean>();
		JSONObject paramsJson = JSON.parseObject(params);
		Long payDepositId = paramsJson.getLong("payDepositId");
		FamilyMemberDto entity = new FamilyMemberDto();
		entity.setBuyId(payDepositId);
		entity.setMemberType(MemberTypeEnum.DEPOSIT.getNo());
		int totl = familyMemberService.destroy(entity);
		System.err.println(totl);

		PayDeposit paySit = service.selectById(payDepositId);
		PayDepositDto mdto = new PayDepositDto();
		mdto = BeanUtil.convert2T(mdto, paySit);

		payDepositTransactionalService.createFamilyMember(paramsJson, mdto, user);

		// 更新新客户信息
		JSONArray newFamilyMembers = paramsJson.getJSONArray("newFamilyMember");
		if (null != newFamilyMembers && newFamilyMembers.size() > 0) {
			String familyMemberStr = (String) newFamilyMembers.get(0);
			FamilyMemberDto familyMemberRow = JSONObject.parseObject(familyMemberStr, FamilyMemberDto.class);
			CustomerDto customerDto = new CustomerDto();
			customerDto.setId(paySit.getCustomerId());
			customerDto.setCustomerName(familyMemberRow.getMemberName());
			customerDto.setPeDocumentType(familyMemberRow.getDocumentType());
			customerDto.setPeDocumentNumber(familyMemberRow.getDocumentNumber());
			customerDto.setCustomerPhone(familyMemberRow.getMobile());
			int count = customerService.saveOrUpdate(customerDto);
			if (count < 0) {
				response.setSuccess(false);
				return response;
			}
		}

		response.setEntity(true);
		response.setSuccess(true);

		return response;
	}

	@Override
	public Response<PayDepositDto> addPayDeposit(String params, User user) throws Exception {
		/**
		 * 认筹 1.保存认筹信息 2.保存家庭成员信息
		 */
		Response<PayDepositDto> response = new Response<PayDepositDto>();
		if (StringUtils.isBlank(params)) {
			response.fail("80000", "参数不能为空！");
			return response;
		}

		// 保存认筹主表信息
		PayDepositDto payDepositDto = JSONObject.parseObject(params, PayDepositDto.class);

		Long projectId = payDepositDto.getProjectId();
//			String projectCode = payDepositDto.getProjectCode();
		if (payDepositDto.getIsPaydeposit().equals(IsPaydepositEnum.YES.getNo())) {
			payDepositDto.setRoomId(1l);
			payDepositDto.setCalculateArea(null);
			payDepositDto.setDiscountPrice(null);
			payDepositDto.setDiscountTotalPrice(null);
			payDepositDto.setFloatingRange(null);
			payDepositDto.setDiscountRate(null);
		} else {
			// 有房认筹,查询客户是否认筹过此房源
			// 过滤未删除、审核中、审核已通过的认筹记录
			PayDepositDto pdDto = new PayDepositDto();
			pdDto.setCustomerId(payDepositDto.getCustomerId());
			pdDto.setRoomId(payDepositDto.getRoomId());
			pdDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			// 审核中的认筹
			pdDto.setAuditStatus(AuditStatusEnum.AUDIT.getNo());
			List<PayDeposit> pdAuditList = service.selectListByDto(pdDto);
			int auditSize = 0;
			if (null != pdAuditList) {
				auditSize = pdAuditList.size();
			}

			// 已通过的认筹
			pdDto.setAuditStatus(AuditStatusEnum.SUCCESS.getNo());
			List<PayDeposit> pdSuccessList = service.selectListByDto(pdDto);
			int successSize = 0;
			if (null != pdSuccessList) {
				successSize = pdSuccessList.size();
			}
			if ((auditSize + successSize) > 0) {
				response.setResultMessage("客户已认筹此房源，不能再次发起认筹!");
				response.setSuccess(false);
				return response;
			}
		}
		if (StringUtils.isNotBlank(payDepositDto.getDepositCode()) && null == payDepositDto.getId()) {
			PayDepositDto dto = new PayDepositDto();
			dto.setDepositCode(payDepositDto.getDepositCode());
			dto.setProjectId(projectId);
			List<PayDeposit> payDeposit = service.selectListByDto(dto);
			if (payDeposit != null && payDeposit.size() != 0) {
				for(PayDeposit p : payDeposit){
					String auditStatus=p.getAuditStatus();
					//合同编号相同 && 非已退回状态 则认为是合同号码重复
					if(!auditStatus.equals(AuditStatusEnum.REJECT.getNo())){
						logger.error("认筹错误", "认筹编号重复");
						response.fail("80000", "认筹编号重复！");
						return response;
					}
				}
			}
		}

		payDepositDto.setAuditStatus(AuditStatusEnum.TOSUBMIT.getNo());
		payDepositDto.setBusinessStatus("1");
		// 公共字段
		payDepositDto.setMerchantId(user.getMerchantId());
		payDepositDto.setCreateUserId(user.getId());
		payDepositDto.setUserCode(user.getUserCode());
		payDepositDto.setDelFlag("0");
		payDepositDto.setUpdateUserId(user.getId());
		payDepositDto.setUpdateTime(new Date());
		if (payDepositDto.getRoomId() != null && payDepositDto.getRoomId().longValue() !=1) {
			ProjectRoom projectRoom = projectRoomService.selectById(payDepositDto.getRoomId());
			if (null != projectRoom) {
				payDepositDto.setAccessCode(projectRoom.getProjectCode());
				payDepositDto.setProjectId(projectRoom.getProjectId());
				payDepositDto.setProjectCode(projectRoom.getProjectCode());
				
				String roomStatus=projectRoom.getRoomStatus();
	            if(RoomStatusEnum.BUY.getNo().equals(roomStatus)){
	            	response.fail("80000", "该房源已被认购！");
	            	return response;
	            }else if(RoomStatusEnum.SIGN.getNo().equals(roomStatus)){
	            	response.fail("80000", "该房源已被签约！");
	            	return response;
	            }else if(RoomStatusEnum.RETAIN.getNo().equals(roomStatus)){
	            	response.fail("80000", "该房源已被保留！");
	            	return response;
	            }else if(RoomStatusEnum.MA.getNo().equals(roomStatus)){
	            	response.fail("80000", "该房源已被销控！");
	            	return response;
	            }else if(RoomStatusEnum.SALEL.getNo().equals(roomStatus)){
	            	response.fail("80000", "该房源暂不可售");
	            	return response;
	            }
			}
		}
		if (payDepositDto.getIsPaydeposit().equals(IsPaydepositEnum.YES.getNo())) {
			// 无房认筹 将客户对应项目的code作为accessCode
			Long customerId = payDepositDto.getCustomerId();
			if (null != customerId) {
				Customer customer = customerService.selectById(customerId);
				if (null != customer) {
					payDepositDto.setProjectId(customer.getProjectId());
					payDepositDto.setProjectCode(customer.getProjectCode());
					payDepositDto.setAccessCode(customer.getProjectCode());
				}
			}
		}
		PayDepositDto mdto = payDepositTransactionalService.addPayDepositWithTransactional(params, user,
				payDepositDto);
		response.success(mdto);
		return response;
	}

	/**
	 * 认筹申请推送消息
	 * 
	 * @param businessAbnormaDto
	 * @param managerMap
	 * @param procInstId
	 * @return
	 */
	@Override
	public CommonResDTO addNotice_RC(PayDepositDto payDepositDto, Map<String, Object> managerMap, String procInstId) {
		CommonResDTO resDto = new CommonResDTO();
		try {
			// 操作人
			String operateUser = "";
			if (null != payDepositDto.getAgentId()) {
				User user = userService.selectById(payDepositDto.getAgentId());
				if (user != null) {
					operateUser = user.getUserName();
				}
			} else {
				logger.info("认筹消息失败,操作人不存在! 认筹Id = " + payDepositDto.getId());
				resDto.setErrorCode("00000");
				resDto.setErrorMsg("认筹消息失败,操作人不存在!");
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}
            Long roomId=null;
            Long customerId=null;
			String roomName = "";
			String customerName = "";
			String projectCode = "";
			String projectName = "";
			PayDeposit payDeposit = service.selectById(payDepositDto.getId());
			if (null != payDeposit) {
				if (IsPaydepositEnum.NO.getNo().equals(payDeposit.getIsPaydeposit())) {
					Project project = projectService.selectById(payDeposit.getProjectId());
					if (null != project) {
						projectCode = project.getProjectCode();
						projectName = project.getProjectName();
					}
					ProjectRoom projectRoom = projectRoomService.selectById(payDeposit.getRoomId());
					if (null != projectRoom) {
						roomId=projectRoom.getId();
						roomName = projectRoom.getCombinedName();
					} else {
						logger.info("认筹消息失败,房源不存在! 认筹Id = " + payDepositDto.getId());
						resDto.setErrorCode("00000");
						resDto.setErrorMsg("认筹消息失败,房源不存在!");
						resDto.setResult(ResultEnum.FAILURE.getNo());
						return resDto;
					}
				}

				// 客户名称
				Customer customer = customerService.selectById(payDeposit.getCustomerId());
				if (null != customer) {
					customerId=customer.getId();
					customerName = customer.getCustomerName();
				} else {
					logger.info("认筹消息失败,客户不存在! 认筹Id = " + payDepositDto.getId());
					resDto.setErrorCode("00000");
					resDto.setErrorMsg("认筹消息失败,客户不存在!");
					resDto.setResult(ResultEnum.FAILURE.getNo());
					return resDto;
				}
			}

			/**
			 * 消息接收人 1、根据审批节点人员确定
			 */
			// 获取当前项目下审批节点人map
			ProjectSettingDto pDto = new ProjectSettingDto();
			pDto.setProjectCode(projectCode);
			ProjectSetting pObj = projectSettingService.selectByDto(pDto);
			Map<String, Object> variables = new HashMap<String, Object>();
			variables.put("projectApprovalUser", pObj.getProjectLeader());
			variables.put("marketingApprovalUser", pObj.getSaleLeader());
			variables.put("caseApprovalUser", pObj.getFieldLeader());
			variables.put("financeApprovalUser", pObj.getFinanceLeader());
			variables.put("saleManagerApprovalUser", pObj.getMaLeader());

			// 获取审批人userId
			List<User> userList = new ArrayList<User>();
			ProcessInstanceHistoryLog processInstanceHistoryLog = historyService.createProcessInstanceHistoryLogQuery(
					procInstId).singleResult();
			BpmnModel model = repositoryService.getBpmnModel(processInstanceHistoryLog.getProcessDefinitionId());
			if (model != null) {
				Collection<FlowElement> flowElements = model.getMainProcess().getFlowElements();
				for (FlowElement e : flowElements) {
					if(e instanceof UserTask){
						List<String> userIds = activitiProcessService.getNodeUserId(payDeposit.getMerchantId(),null,processInstanceHistoryLog.getProcessDefinitionId(),e.getId());
						for(String userId : userIds){
							User user = new User();
							user.setId(Long.valueOf(userId));
							userList.add(user);
						}
					}
				}
			}
			if (userList.size() == 0) {
				logger.info("认筹消息失败,待发送客户不存在! 认筹Id = " + payDepositDto.getId());
				resDto.setErrorCode("00000");
				resDto.setErrorMsg("认筹消息失败,待发送客户不存在!");
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}

			// 认筹, 获取字典表dictionary_value = 'NT07' 的消息模板
			// 消息模板: 认筹审批申请、房号：${roomName}；客户：${customer}；经纪人：${agent}
			String msgTemp = "认筹审批申请。房号：${roomName}；客户：${customer}；经纪人：${agent}";
			String sendMsg = "";
			DictionaryDto dicDto = new DictionaryDto();
			dicDto.setDictionaryValue("NT07");
			Dictionary dic = dictionaryService.selectByDto(dicDto);
			if (dic != null) {
				msgTemp = dic.getDictionaryName();
			}
			if (IsPaydepositEnum.NO.getNo().equals(payDeposit.getIsPaydeposit())) {
				sendMsg = msgTemp.replace("${roomName}", roomName).replace("${customer}", customerName)
						.replace("${agent}", operateUser);
			} else {
				sendMsg = msgTemp.replace("${roomName}", "无").replace("${customer}", customerName)
						.replace("${agent}", operateUser);
			}
			// 创建提醒消息及消息发送人信息
			Map<String, String> noticeParamMap = new HashMap<String, String>();
			noticeParamMap.put("noticeDicId", "170");
			noticeParamMap.put("noticeTempType", "NT07");
			noticeParamMap.put("sendMsg", sendMsg);
			noticeParamMap.put("title", "认筹审批申请");
			noticeParamMap.put("merchantId", String.valueOf(payDepositDto.getMerchantId()));
			noticeParamMap.put("projectCode", payDepositDto.getProjectCode());
			noticeParamMap.put("userCode", payDepositDto.getUserCode());
			noticeParamMap.put("accessCode", payDepositDto.getAccessCode());
			noticeParamMap.put("createUserId", String.valueOf(payDepositDto.getCreateUserId()));
			/*
			 * (ym) 提醒内容增加超链接 start
			 * */
			Map<String,String> replaceValuesMap=new HashMap<String,String>();
			replaceValuesMap.put(MsgUtil.ROOM_ID, roomId==null?"":String.valueOf(roomId));
			replaceValuesMap.put(MsgUtil.ROOM_NAME, roomName);
			replaceValuesMap.put(MsgUtil.CUSTOMER_ID, customerId==null?"":String.valueOf(customerId));
			replaceValuesMap.put(MsgUtil.CUSTOMER_NAME,customerName);
			replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
			replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
	    	noticeParamMap.put("replaceValues", MsgUtil.getReplaceValues(replaceValuesMap));
	    	/*
			 * (ym) 提醒内容增加超链接 end
			 * */
			NoticeDto noticeDto = noticeService.createNotice(noticeParamMap, userList, null);
			// 推送消息待处理......
			resDto = noticeService.pushMsg(projectCode, projectName, noticeDto, "认筹审批申请");
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("认筹消息异常,认筹Id = " + payDepositDto.getId(), e);
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("认筹消息异常!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		return resDto;
	}

	/**
	 * 退认筹push消息推送
	 */
	@Override
	public CommonResDTO addNotice_TRC(BusinessAbnormaDto businessAbnormaDto, Map<String, Object> managerMap,
			String procInstId) {
		CommonResDTO resDto = new CommonResDTO();
		try {
			// 操作人
			String operateUser = "";
			
			Long roomId=null;
			Long customerId=null;
			String roomName = "";
			String customerName = "";
			String projectCode = "";
			String projectName = "";
			PayDeposit payDeposit = null;
			if (null != businessAbnormaDto.getBusinessId()) {
				payDeposit = service.selectById(businessAbnormaDto.getBusinessId());
				if (null != payDeposit) {
					if (IsPaydepositEnum.NO.getNo().equals(payDeposit.getIsPaydeposit())) {
						Project project = projectService.selectById(payDeposit.getProjectId());
						if (null != project) {
							projectCode = project.getProjectCode();
							projectName = project.getProjectName();
						}
						ProjectRoom projectRoom = projectRoomService.selectById(payDeposit.getRoomId());
						if (null != projectRoom) {
							roomId=projectRoom.getId();
							roomName = projectRoom.getCombinedName();
						} else {
							logger.info("退认筹消息失败,房源不存在! 退认筹Id = " + businessAbnormaDto.getId());
							resDto.setErrorCode("00000");
							resDto.setErrorMsg("退认筹消息失败,房源不存在!");
							resDto.setResult("0");
							return resDto;
						}
					}

					// 客户名称
					Customer customer = customerService.selectById(payDeposit.getCustomerId());
					if (null != customer) {
						customerId=customer.getId();
						customerName = customer.getCustomerName();
					} else {
						logger.info("退认筹消息失败,客户不存在! 退认筹Id = " + businessAbnormaDto.getId());
						resDto.setErrorCode("00000");
						resDto.setErrorMsg("退认筹消息失败,客户不存在!");
						resDto.setResult("0");
						return resDto;
					}
					
					if (null !=payDeposit.getAgentId()) {
						User user = userService.selectById(payDeposit.getAgentId());
						if (user != null) {
							operateUser = user.getUserName();
						}
					} else {
						logger.info("退认筹消息失败,认筹经济人不存在! 退认筹Id = " + businessAbnormaDto.getId());
						resDto.setErrorCode("00000");
						resDto.setErrorMsg("退认筹消息失败,操作人不存在!");
						resDto.setResult("0");
						return resDto;
					}
				}
			} else {
				logger.info("退认筹消息失败,认筹信息不存在! 退认筹Id = " + businessAbnormaDto.getId());
				resDto.setErrorCode("00000");
				resDto.setErrorMsg("退认筹消息失败,认筹信息不存在!");
				resDto.setResult("0");
				return resDto;
			}

			/**
			 * 消息接收人 1、根据审批节点人员确定
			 */
			// 获取当前项目下审批节点人map
			ProjectSettingDto pDto = new ProjectSettingDto();
			pDto.setProjectCode(projectCode);
			ProjectSetting pObj = projectSettingService.selectByDto(pDto);
			Map<String, Object> variables = new HashMap<String, Object>();
			variables.put("projectApprovalUser", pObj.getProjectLeader());
			variables.put("marketingApprovalUser", pObj.getSaleLeader());
			variables.put("caseApprovalUser", pObj.getFieldLeader());
			variables.put("financeApprovalUser", pObj.getFinanceLeader());
			variables.put("saleManagerApprovalUser", pObj.getMaLeader());

			// 获取审批人userId
			List<User> userList = new ArrayList<User>();
			ProcessInstanceHistoryLog processInstanceHistoryLog = historyService.createProcessInstanceHistoryLogQuery(
					procInstId).singleResult();
			BpmnModel model = repositoryService.getBpmnModel(processInstanceHistoryLog.getProcessDefinitionId());
			if (model != null) {
				Collection<FlowElement> flowElements = model.getMainProcess().getFlowElements();
				for (FlowElement e : flowElements) {
					if(e instanceof UserTask){
						List<String> userIds = activitiProcessService.getNodeUserId(payDeposit.getMerchantId(),null,processInstanceHistoryLog.getProcessDefinitionId(),e.getId());
						for(String userId : userIds){
							User user = new User();
							user.setId(Long.valueOf(userId));
							userList.add(user);
						}
					}
				}
			}
			if (userList.size() == 0) {
				logger.info("退认筹消息失败,待发送客户不存在! 退认筹Id = " + businessAbnormaDto.getId());
				resDto.setErrorCode("00000");
				resDto.setErrorMsg("退认筹消息失败,待发送客户不存在!");
				resDto.setResult("0");
				return resDto;
			}

			// 无房认筹, 获取字典表dictionary_value = 'NT14' 的消息模板
			// 消息模板: 退认筹审批申请、房号：${roomName}；客户：${customer}；经纪人：${agent}
			String msgTemp = "退认筹审批申请。房号：${roomName}；客户：${customer}；经纪人：${agent}";
			String sendMsg = "";
			DictionaryDto dicDto = new DictionaryDto();
			dicDto.setDictionaryValue("NT14");
			Dictionary dic = dictionaryService.selectByDto(dicDto);
			if (dic != null) {
				msgTemp = dic.getDictionaryName();
			}
			sendMsg = msgTemp.replace("${roomName}", roomName).replace("${customer}", customerName)
					.replace("${agent}", operateUser);
			// 创建提醒消息及消息发送人信息
			Map<String, String> noticeParamMap = new HashMap<String, String>();
			noticeParamMap.put("noticeDicId", "177");
			noticeParamMap.put("noticeTempType", "NT14");
			noticeParamMap.put("sendMsg", sendMsg);
			noticeParamMap.put("title", "退认筹审批申请");
			noticeParamMap.put("merchantId", String.valueOf(businessAbnormaDto.getMerchantId()));
			noticeParamMap.put("projectCode", projectCode);
			noticeParamMap.put("userCode", businessAbnormaDto.getUserCode());
			noticeParamMap.put("accessCode", businessAbnormaDto.getAccessCode());
			noticeParamMap.put("createUserId", String.valueOf(businessAbnormaDto.getCreateUserId()));
			/*
			 * (ym) 提醒内容增加超链接 start
			 * */
			Map<String,String> replaceValuesMap=new HashMap<String,String>();
			replaceValuesMap.put(MsgUtil.ROOM_ID, roomId==null?"":String.valueOf(roomId));
			replaceValuesMap.put(MsgUtil.ROOM_NAME, roomName);
			replaceValuesMap.put(MsgUtil.CUSTOMER_ID, customerId==null?"":String.valueOf(customerId));
			replaceValuesMap.put(MsgUtil.CUSTOMER_NAME,customerName);
			replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
			replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
	    	noticeParamMap.put("replaceValues", MsgUtil.getReplaceValues(replaceValuesMap));
	    	/*
			 * (ym) 提醒内容增加超链接 end
			 * */
			NoticeDto noticeDto = noticeService.createNotice(noticeParamMap, userList, null);
			// 推送消息待处理......
			resDto = noticeService.pushMsg(projectCode, projectName, noticeDto, "退认筹审批申请");
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("退认筹消息异常,延期业务Id = " + businessAbnormaDto.getId(), e);
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("退认筹消息异常!");
			resDto.setResult("0");
			return resDto;
		}
		return resDto;
	}

	@Override
	public int getCustomerEntity(String bugType, Long busId, Long customerId, Long userId) {
		return customerService.getCustomerEntity(bugType, busId, customerId, userId);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.emm.yixun.customer.service.PayDepositServiceFacade#selectPayDepositCustomer(java.lang.Long)
	 */
	@Override
	public Response<PayDepositDto> selectPayDepositCustomer(Long id) {
		Response<PayDepositDto> response = new Response<PayDepositDto>();
		try {
			PayDepositDto payDepositDto = service.selectPayDepositCustomer(id);
			if (null == payDepositDto) {
				response.setSuccess(false);
				return response;
			}
			response.success(payDepositDto);
		} catch (Exception e) {
			response.setSuccess(false);
			logger.error("查询数据错误：{}", e);
		}
		return response;
	}

}
